﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace WebAPI.CustomFilter
{
    /// <summary>
    /// 程序异常过滤器
    /// </summary>
    public class ExceptionFilter : IAsyncExceptionFilter
    {
        public Task OnExceptionAsync(ExceptionContext context)
        {
            //context.Exception代表异常信息对象
            //如果给 context.ExceptionHandled赋值为true，则其他ExceptionFilter不会被执行
            //context.Result的值会被输出到客户端
            File.AppendAllTextAsync("D:/error.log", context.Exception.ToString());

            JsonResult result = new JsonResult(new { code = 500, message = context.Exception.ToString()});
            context.Result = result;    //context.Result的值会被输出到客户端
            context.ExceptionHandled = true;  //其他ExceptionFilter不会被执行
            return Task.CompletedTask;
        }
    }

}
